//
//  DeviceManager.m
//  Shion
//
//  Created by Chris Karr on 12/17/07.
//  Copyright 2007-2008 Audacious Software. All rights reserved.
//

#import "DeviceManager.h"
#import "InsteonDeviceCommand.h"
#import "InsteonOnCommand.h"
#import "InsteonOffCommand.h"
#import "InsteonBrightenCommand.h"
#import "InsteonDimCommand.h"
#import "InsteonInfoCommand.h"
#import "InsteonLightStatusRequestCommand.h"

@implementation DeviceManager

- (DeviceManager *) init
{
	if (self = [super init])
	{
		powerLinc = [[PowerLincUSB alloc] init];
		
		pendingCommands = [[NSMutableArray alloc] init];
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(execute:) name:SHION_INSTRUCTION object:nil];
		[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(sendCommand:) userInfo:nil repeats:NO];
	}
	
	return self;
}

- (void) sendCommand:(NSTimer *) theTimer
{
	if ([pendingCommands count] > 0)
	{
		if ([powerLinc isReady])
		{
			InsteonDeviceCommand * command = [pendingCommands objectAtIndex:0];
			
			[powerLinc sendCommand:command];
			[pendingCommands removeObject:command];
		}
	}
	
	[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(sendCommand:) userInfo:nil repeats:NO];
}

- (void) execute: (NSNotification *) msg
{
	NSDictionary * cmd = (NSDictionary *) [msg object];
	
	InsteonDeviceCommand * command = nil;

	NSString * action = [cmd valueForKey:@"action"];
	NSNumber * level = [cmd valueForKey:@"level"];
	
	if ([action isEqual:@"set"])
	{
		command = [[InsteonOnCommand alloc] init];
		
		if (level != nil)
			[(InsteonOnCommand *) command setLevel:[level integerValue]];
	}
	else if ([action isEqual:@"query"])
		command = [[InsteonLightStatusRequestCommand alloc] init];
	else
	{
		NSLog (@"unknown command");
		return;
	}
		
	command.address = [cmd valueForKey:@"address"];
	
	for (InsteonDeviceCommand * c in pendingCommands)
	{
		if ([c isMemberOfClass:[command class]] && [c.address isEqual:command.address])
			return;
	}
		
	if ([action isEqual:@"query"])
		[pendingCommands addObject:command];
	else
		[pendingCommands insertObject:command atIndex:0];
}

@end
